package com.sunplus.system.controller.system;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunplus.common.core.domain.entity.SysUser;
import com.sunplus.common.utils.file.FileUtils;
import com.sunplus.system.domain.SysRoleMenu;
import com.sunplus.system.service.impl.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sunplus.common.annotation.Log;
import com.sunplus.common.constant.UserConstants;
import com.sunplus.common.core.controller.BaseController;
import com.sunplus.common.core.domain.AjaxResult;
import com.sunplus.common.core.domain.entity.SysRole;
import com.sunplus.common.core.domain.model.LoginUser;
import com.sunplus.common.enums.BusinessType;
import com.sunplus.common.utils.SecurityUtils;
import com.sunplus.common.utils.ServletUtils;
import com.sunplus.common.utils.poi.ExcelUtil;
import com.sunplus.framework.web.service.TokenService;
import com.sunplus.system.service.ISysRoleService;
import com.sunplus.system.service.ISysUserService;

/**
 * 角色信息
 */
@RestController
@RequestMapping({"/admin/right_RoleMgr", "/admin/right_roleMgr", "/admin/right_RoleRightMgr"})
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    /**
     * 菜单文件路径
     */
    @Value("${menu.location}")
    private String menuLocation;

    //    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @PostMapping(value = "/listPain")
    public AjaxResult listPain(SysRole role) {
        startPage();
        List<Map> list = roleService.selectRoleList(role);
        JSONObject data = getDataTable(list);
        data.put("ButtonRight", "add,edit,del,view,SetRight");
        return AjaxResult.success(data);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @GetMapping("/export")
    public AjaxResult export(SysRole role) {
        List<Map> list = roleService.selectRoleList(role);
        ExcelUtil<Map> util = new ExcelUtil<>(Map.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable String roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/Add")
    public AjaxResult add(@Validated SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setGroupID(SecurityUtils.getLoginUser().getUser().getGroupID());
        role.setCreateUser(SecurityUtils.getLoginUser().getUser().getPID());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@Validated SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateUser(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/BatchDelete")
    public AjaxResult remove(@RequestParam String[] ids) {
        return toAjax(roleService.deleteRoleByIds(ids));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return AjaxResult.success(roleService.selectRoleAll());
    }

    /**
     * 根据用户编号获取角色信息
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @PostMapping(value = "/GetUserRole")
    public AjaxResult getUserRole(@RequestParam("userpid") String userpid) {
        JSONObject obj = new JSONObject();
        obj.put("rows", roleService.selectRoleAll());
        obj.put("roles", roleService.selectRoleListByUserId(userpid));
        return AjaxResult.success(obj);
    }

    /**
     * 修改用户角色
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @PostMapping(value = "/SetUserRole")
    public AjaxResult setUserRole(@RequestParam String userpid, @RequestParam String[] RoleIDs) {
        SysUser user = new SysUser();
        user.setPID(userpid);
        user.setRoleIds(RoleIDs);
        user.setGroupID(SecurityUtils.getLoginUser().getUser().getGroupID());
        user.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
        return toAjax(roleService.updateUserRole(user));
    }

    /**
     * 查询角色权限
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @PostMapping(value = "/GetRoleRight")
    public AjaxResult getRoleRight(@RequestParam("RoleID") String RoleID) throws Exception {
//        File jsonFile = ResourceUtils.getFile("classpath:static/start/json/menu.js");
//        String menu = FileUtils.readFileToString(jsonFile, "utf-8");
//        JSONArray menuObj = JSONArray.parseArray("[{\"id\":\"0\",\"name\":\"全部\",\"type\":\"other\",\"icon\":null,\"title\":\"全部\",\"jump\":null,\"spread\":true,\"site\":null,\"buttonStr\":null,\"name\":\"全部\",\"title\": \"全部\",\"type\": \"other\"}]");
//        menuObj.getJSONObject(0).put("list", JSONArray.parseArray(menu));

        File jsonFile = ResourceUtils.getFile(menuLocation);
        String menu = FileUtils.readFileToString(jsonFile, "utf-8");
        JSONArray menuObj = JSONArray.parseArray(menu);
        JSONObject obj = new JSONObject();
        obj.put("MenuAll", menuObj);
        obj.put("RoleRight", roleService.selectRoleMenuByRoleID(RoleID).stream().map(SysRoleMenu::getFunctionRight).collect(Collectors.joining(",")));
        return AjaxResult.success(obj);
    }

    /**
     * 修改角色权限
     */
//    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @PostMapping(value = "/SetRoleRight")
    public AjaxResult setRoleRight(@RequestParam String RoleID, @RequestParam String RoleRight) throws Exception {
        SysRole role = new SysRole();
        role.setPID(RoleID);
        role.setGroupID(SecurityUtils.getLoginUser().getUser().getGroupID());
        role.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
        role.setMenuIds(roleData(JSONArray.parseArray(RoleRight)).split("&"));
        return toAjax(roleService.updateRoleMenu(role));
    }

    private String roleData(JSONArray menuArray) {
        String role = "";
        for (int i = 0; i < menuArray.size(); i++) {
            JSONObject menu = menuArray.getJSONObject(i);
            if ("page".equals(menu.getString("type")) && !StringUtils.isEmpty(menu.getString("jump"))) {
                role += menu.getString("id") + "#";
            }
            if ("button".equals(menu.getString("type"))) {
                role += menu.getString("id") + ",";
            }
            if (menu.getJSONArray("list") != null) {
                role += roleData(menu.getJSONArray("list")) + "&";
            }
        }
        return StringUtils.isEmpty(role) ? "" : role.substring(0, role.length() - 1);
    }

    @PostMapping("/GetButtonRight")
    public AjaxResult getButtonRight() throws Exception {
        return AjaxResult.success((Object) "<button class=\"layui-btn layuiadmin-btn-list\" data-type=\"add\">添加</button><button class=\"layui-btn layuiadmin-btn-list\" data-type=\"del\">删除</button>");
    }

    @PostMapping("/GetUserRight")
    public AjaxResult getUserRight() throws Exception {
        JSONObject user = new JSONObject();
        user.put("CustomerRight", 0);
        return AjaxResult.success(user);
    }

}
